package com.atguigu.hosp.msm.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.atguigu.hosp.msm.config.ConstantPropertiesUtils;
import com.atguigu.hosp.msm.service.MsmService;
import com.atguigu.hosp.msm.utils.RandomUtilsCode;
import com.atguigu.yygh.vo.msm.MsmVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class MsmServiceImpl implements MsmService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void send(String phone) {
        // 测试调用短信api
        DefaultProfile defaultProperty = DefaultProfile.getProfile(ConstantPropertiesUtils.REGIONID, ConstantPropertiesUtils.KEYID, ConstantPropertiesUtils.KEYSECRET);
        IAcsClient iAcsClient = new DefaultAcsClient(defaultProperty);

        // 请求接口参数
        CommonRequest commonRequest = new CommonRequest();
        commonRequest.setMethod(MethodType.POST);
        commonRequest.setDomain("dysmsapi.aliyuncs.com");
        commonRequest.setVersion("2017-05-25");// 接口版本
        commonRequest.setAction("SendSms");// 接口名
        commonRequest.putQueryParameter("PhoneNumbers", phone);
        String signName = ConstantPropertiesUtils.SIGNNAME;
        commonRequest.putQueryParameter("SignName", signName);
        commonRequest.putQueryParameter("TemplateCode", ConstantPropertiesUtils.TEMPLATECODE);

        // 也使用json工具制作参数
        Map<String, String> map = new HashMap<>();
        String sixBitRandom = RandomUtilsCode.getSixBitRandom();

        // 将验证码存入缓存
        redisTemplate.opsForValue().set("yygh:msm:code:" + phone, sixBitRandom);
        map.put("code", sixBitRandom);
        String json = JSON.toJSONString(map);
        log.info("短信验证码code---->"+map);
        commonRequest.putQueryParameter("TemplateParam", json);

        // 发送
        CommonResponse commonResponse = null;
        try {
            // 调用发送短信功能
            commonResponse = iAcsClient.getCommonResponse(commonRequest);
            System.out.println("commonResponse = " + commonResponse);
            // 捕捉异常信息
        } catch (ClientException e) {
            e.printStackTrace();
        }


    }

    /**
     * MQ发送短信的封装
     * @param msmVo
     * @return
     */
    @Override
    public boolean send(MsmVo msmVo) {
        if(!StringUtils.isEmpty(msmVo.getPhone())) {
            String code = (String)msmVo.getParam().get("code");
               this.send(msmVo.getPhone());
        }
        return false;
    }





}
